package com.kristin.classLoader;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @ClassName MyClassLoader
 * @Description TODO
 * @Author Kristin
 * @Date 2020/09/08 11:27:09
 * @Version 1.0.0
 */
public class MyClassLoader extends ClassLoader {

    private String rootDir;

    public MyClassLoader(String rootDir) {
        this.rootDir = rootDir;
    }

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        String className = name.substring(name.lastIndexOf(".") + 1 ) + ".class";
        String classFile = rootDir + File.separator + className;
        byte[] classData = null;
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(classFile);
            classData = new byte[fis.available()];
            fis.read(classData,0 , classData.length);
            return defineClass(name, classData, 0 , classData.length);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fis != null){
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return super.findClass(name);
    }

    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
        MyClassLoader classLoader = new MyClassLoader("E:\\学习\\krstin-data\\project\\base\\target\\classes\\classes");
        Class c = classLoader.loadClass("com.kristin.classLoader.Person");
        Object object = c.newInstance();
        Method getNameMethod = c.getMethod("getName");
        Method getAgeMethod = c.getMethod("getAge");
        System.out.println("name:" + getNameMethod.invoke(object) + ",age:" + getAgeMethod.invoke(object));
        System.out.println("类加载器为：" + object.getClass().getClassLoader());
    }

}
